<template>
  <div class="container">
    <editPageNew
      ref="editPage"
      :showMore="showMore"
      :rightBtnArr="rightBtnArr"
      :moreBtnArr="moreBtnArr"
      :stepConfig="stepConfig"
      :creatInfo="creatInfo"
      showTopTitle
    >
      <template slot="editPageTitle">
        <span class="title"> {{ pageName }} {{ code }}</span>
      </template>
      <div class="plan-title">
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span>{{ title }}</span>
          <el-link
            v-if="showBtn"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <el-input
            type="text"
            maxlength="64"
            v-model="title"
            @blur="loseFocus"
            show-word-limit
            placeholder="请输入标题"
            clearable
            ref="mark"
            ><template slot="prepend"
              >标题</template
            ></el-input
          >
        </div>
      </div>
      <dialogPublic
        title="帮助提示"
        noFootBtn
        width="800"
        :show.sync="visibleHelp"
      >
        <p>
          请您查收短信并完成签名，若已签名，请点页面右上角按钮或下方链接刷新签名结果。
        </p>
        <el-link @click="refreshStatus" type="primary" :underline="false"
          >刷新签名状态</el-link
        >
      </dialogPublic>
      <electronicSign
        :electronicData="electronicData"
        :electronicForm="electronicForm"
        @electronicSignAfter="electronicSignAfter"
        ref="electronicSign"
      ></electronicSign>
      <sign :showTemporary="showTemporary" @doSign="doSign" ref="sign"></sign>
      <dialogPublic
        title="工单编号"
        :show.sync="showDialogWork"
        @doSubmit="dialogSubmitWork"
        @doClose="() => (showDialogWork = false)"
        fullscreen
      >
        <workOrder ref="workOrderTable" />
      </dialogPublic>
      <remarkOrCheck
        v-if="showRemarks"
        :workTicketId="id"
        :dialogTitle="dialogTitle"
        ref="remarkOrCheck"
      ></remarkOrCheck>
      <dialogPublic
        title="查看流程"
        :show.sync="showDialogFlow"
        noFootBtn
        appendTobody
        fullscreen
      >
        <workFlow
          v-if="showDialogFlow"
          workflowCode="ticket_work_status_thirdticket"
          :isDetails="true"
          :currentFlowData="formDataFlow"
        ></workFlow>
      </dialogPublic>
      <el-collapse v-model="activeNames">
        <el-collapse-item class="basic" name="1" v-if="status >= 1">
          <template slot="title"> 基本信息 </template>
          <editForm
            class="info-data"
            :formConfig="basicConfig"
            ref="basicForm"
            :formData="basicFormData"
          >
            <template #number="{}">
              <div class="sign-name-list">
                <span class="text-span" title="共几人">
                  <label class="text-label">共</label>
                  <el-input
                    class="text-input"
                    type="text"
                    v-model="number"
                    :disabled="true"
                  />
                  <span class="text-label">人</span>
                </span>
              </div>
            </template>
            <template #orderCode="{ editFormInfo }">
              <div class="input-link">
                <el-input
                  placeholder="请选择工单编号"
                  size="mini"
                  :readonly="true"
                  v-model="editFormInfo.orderCode"
                  @click.native="
                    goWorkOrder(editFormInfo.orderId, editFormInfo.orderType)
                  "
                >
                  <el-button
                    v-if="!workOrderDisable"
                    slot="append"
                    class="link-button"
                    @click.stop="getTicketNum"
                    :disabled="workOrderDisable"
                    >选择</el-button
                  >
                </el-input>
              </div>
            </template>
          </editForm>
        </el-collapse-item>
        <el-collapse-item name="5" v-if="status >= 5">
          <template slot="title"> 许可信息 </template>
          <editForm
            class="license info-data"
            :formConfig="licenseConfig"
            ref="licenseForm"
            :formData="licenseFormData"
          ></editForm>
        </el-collapse-item>
        <el-collapse-item
          class="end-of-work-ticket"
          name="7"
          v-if="status >= 7"
        >
          <template slot="title"> 工作票终结信息 </template>
          <editForm
            class="info-data"
            :formConfig="endOfTicketConfig"
            ref="endOfWorkTicketForm"
            :formData="endOfTicketFormData"
          ></editForm>
        </el-collapse-item>
        <el-collapse-item name="9" v-if="showJSA">
          <template slot="title"> JSA附件信息 </template>
          <div style="width: 60%; margin: 0 auto">
            <attachFormNew
              :disabled="false"
              isDelete
              coverFile
              isInstantUpload
              :attachSetting="attachSetting"
              ref="attachForm"
            ></attachFormNew>
          </div>
        </el-collapse-item>
        <el-collapse-item name="8" v-if="showFlow">
          <template slot="title"> 审批信息 </template>
          <workFlow
            :isDetails="false"
            workflowCode="ticket_work_status_thirdticket"
            :beforeFlowSubmitErr="beforeFlowSubmitErr"
            :currentFlowData="formDataFlow"
            ref="workFlow"
            @submitSuccess="workFlowSuccess"
            :beforeFlowSubmit="beforeFlowSubmit"
          ></workFlow>
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
    <dialogPbc
      title="提交"
      :show.sync="show"
      @doClose="() => (show = false)"
      width="30%"
    >
      <div style="margin-left: 20px; padding: 10px 0">{{ content }}</div>
      <template slot="footer__btn" v-if="judgType == 'A1'">
        <el-button
          size="mini"
          class="dialog-footer__btn"
          @click="() => (show = false)"
          >再想想</el-button
        >
        <el-button
          size="mini"
          class="dialog-footer__btn"
          @click="continueSubmit"
          >不办理，坚持提交</el-button
        >
        <el-button
          type="primary"
          class="dialog-footer__btn"
          size="mini"
          @click="goOperateTicket('operation_a')"
          >去办理</el-button
        >
      </template>
      <template slot="footer__btn" v-else-if="judgType == 'A2'">
        <el-button
          size="mini"
          class="dialog-footer__btn"
          @click="() => (show = false)"
          >再想想</el-button
        >
        <el-button
          type="primary"
          class="dialog-footer__btn"
          size="mini"
          @click="goOperateTicketDetail('A')"
          >去归档</el-button
        >
      </template>
      <template slot="footer__btn" v-else-if="judgType == 'B1'">
        <el-button
          size="mini"
          class="dialog-footer__btn"
          @click="() => (show = false)"
          >再想想</el-button
        >
        <el-button
          type="primary"
          class="dialog-footer__btn"
          size="mini"
          @click="goOperateTicket('operation_b')"
          >去办理</el-button
        >
      </template>
      <template slot="footer__btn" v-else-if="judgType == 'B2'">
        <el-button
          size="mini"
          class="dialog-footer__btn"
          @click="goOperateTicket('operation_a')"
          >还需继续办理B票，去办理</el-button
        >
        <el-button
          type="primary"
          class="dialog-footer__btn"
          size="mini"
          @click="continueSubmit"
          >已全部办理，提交</el-button
        >
      </template>
      <template slot="footer__btn" v-else-if="judgType == 'B3'">
        <el-button
          size="mini"
          class="dialog-footer__btn"
          @click="() => (show = false)"
          >再想想</el-button
        >
        <el-button
          type="primary"
          class="dialog-footer__btn"
          size="mini"
          @click="goOperateTicketDetail('B')"
          >去归档</el-button
        >
      </template>
    </dialogPbc>
  </div>
</template>
<script>
import sign from "../process/sign";
import electronicSign from "../process/electronicSign";
import remarkOrCheck from "../process/remarkOrCheck";
import workOrder from "../process/workOrder";
import dialogPbc from "./dialogPbc";
import {
  queryOrderById,
  getDispatchApi,
} from "@/api/twoTicketManagement/workTicket.js";
import {
  getWorkTicketInfo,
  getSampleTicketData,
  getWorkTicketData,
  submitTdWorkTicket,
  saveTdWorkTicket,
  tdPermitSave,
  tdTicketEndSave,
  getDeptByOrgId,
  printTdById,
  updatePreview,
  deleteSign,
  getPower,
  checkTimeOut,
  checkRelation,
  checkRelationPro,
} from "@/api/twoTicketManagement/workTicket.js";
export default {
  components: {
    sign,
    electronicSign,
    remarkOrCheck,
    workOrder,
    dialogPbc,
  },
  data() {
    return {
      orderWorkDeptPoList: [],
      workflowData: null,
      content: "是否需要办理操作票A票?",
      show: false,
      judgType: "",
      operateTicketAId: "",
      operateAGroup: "",
      operateTicketBId: "",
      operateBGroup: "",
      attachSetting: {},
      operationAticket: null,
      operationBticket: null,
      toSubmit: false,
      beforeFlowSubmitErr: "",
      updateTime: "", // 更新时间
      workLocationOption: [],
      locationList: [],
      pageName: "",
      hidePreviewBtn: true,
      hideSaveBtn: true,
      hideDeleteBtn: true,
      hideOperationBtn: true,
      btnPowerList: [],
      showTemporary: false,
      showFlow: false,
      orgArr: [], // 填写状态工作负责人及工作班成员所属工作班组
      extraOrgArr: [], // 填写状态额外所选工作班组
      creatInfo: {}, // 右下角创建信息
      externalFlag: "", //是否外单位， 0 非外单位 1 外单位 -1 临时人员
      showMore: false, // 显示更多
      visibleHelp: false, // 显示电子签名帮助提示
      electronicForm: [], // 电子签表格数据 姓名 手机号
      electronicData: {}, // 电子签其他数据
      signType: 0, // 签名方式 1表示电子签，0表示账号密码签
      accounts: 1, // 电子签名状态 2表示已让用户去签名 1表示未签名，0表示已签名
      isSave: 1, // 信息是否已保存 1未保存，0已保存
      isReSign: 1, // 重新签名标识， 1表示不重新签名，0表示去重新签名
      previewed: 1, // 预览状态 1表示未预览 0表示已预览
      isEdit: 1, // 是否修改 1表示未修改 0表示已修改
      workFlowIdList: {},
      workFlowTypeList: {},
      workOrderDisable: false, // 选择工单
      endDisable: false,
      pageType: "", // 页面类型
      nowStepIndex: 0, // 步骤下标
      status: 1, // 工作票状态
      id: "", // 工作票id
      code: "暂无票号", // 工作票票号
      dialogTitle: "", // 弹框标题
      showDialogWork: false, // 工单编号
      showDialogFlow: false, // 流程弹框
      showRemarks: false, // 备注弹框
      doRemarkShow: false,
      formData: {},
      number: 0, // 人数总计
      number0: 0, // 工作负责人数量
      number1: 0, // 工作班成员数量
      userOption: [],
      workTeamOption: [],
      activeNames: [],
      title: "",
      showInput: false,
      showBtn: true,
      createBy: "",
      deptId: "",
      unit: "",
      unitName: "",
      beforeFlowSubmit: {
        methods: async (data) => {
          this.workflowData = data;
          let res = false;
          if (this.status == 1) {
            if (this.title) {
              await this.save(1);
              await this.submit();
              if (this.formDataFlow.workTicketId) {
                this.$utils.addOperateLog(this.id, `提交了${this.pageName}`);
                res = Object.assign(this.formDataFlow, {
                  createBy: this.createBy,
                  deptId: this.deptId,
                  unit: this.unit,
                  unitName: this.unitName,
                });
              } else {
                this.$message.warning("未填写完整");
              }
            } else {
              this.$message.warning("标题不能为空");
              this.editTitle();
            }
          } else if (data.operation == "32") {
            if (this.previewed == 1 && this.status == 5) {
              this.$message.warning("请先预览。");
            } else {
              await this.toCheckTimeOut();
              if (this.toSubmit) {
                this.beforeFlowSubmitErr = "未填写完整";
                await this.doSubmits();
                if (this.formDataFlow.workTicketId) {
                  if (this.status == 5 && this.operationAticket == 0) {
                    this.show = true;
                    this.content = "是否需要办理操作票A票？";
                    this.judgType = "A1";
                  } else if (this.status == 5 && this.operationAticket == 1) {
                    this.show = true;
                    this.content =
                      "您办理的操作票A票还未归档，必须先归档后才能继续";
                    this.judgType = "A2";
                  } else if (
                    this.status == 7 &&
                    this.operationBticket == 0 &&
                    this.operationAticket != 0
                  ) {
                    this.show = true;
                    this.content = "您还未办理操作票B票，是否现在去办理？";
                    this.judgType = "B1";
                  } else if (
                    this.status == 7 &&
                    this.operationBticket == 1 &&
                    this.operationAticket != 0
                  ) {
                    this.show = true;
                    this.content =
                      "您办理的操作票B票还未归档，必须先归档后才能继续";
                    this.judgType = "B3";
                  } else if (
                    this.status == 7 &&
                    this.operationBticket == 2 &&
                    this.operationAticket != 0
                  ) {
                    this.show = true;
                    this.content = "操作票B票是否已全部办理完结？";
                    this.judgType = "B2";
                  } else {
                    this.$utils.addOperateLog(
                      this.id,
                      `审批了${this.pageName}`
                    );
                    res = Object.assign(this.formDataFlow, {
                      createBy: this.createBy,
                      deptId: this.deptId,
                      unit: this.unit,
                      unitName: this.unitName,
                    });
                  }
                } else {
                  this.$message.warning("未填写完整");
                }
              } else {
                this.beforeFlowSubmitErr = "";
              }
            }
          } else {
            if (data.operation == "16") {
              this.$utils.addOperateLog(this.id, `废弃了${this.pageName}`);
            } else if (data.operation == "1") {
              this.$utils.addOperateLog(this.id, `驳回了${this.pageName}`);
            }
            this.formDataFlow = {
              id: this.id,
              workTicketId: this.id,
              title: this.title,
              createBy: this.createBy,
              deptId: this.deptId,
              unit: this.unit,
              unitName: this.unitName,
            };
            res = this.formDataFlow;
          }
          return res;
        },
      },
      // 基本信息表单
      basicConfig: {
        labelWidth: "200px",
        itemArr: [
          {
            label: "工作票类型:",
            prop: "type$",
            type: "text",
            span: 12,
            required: true,
            disabled: true,
          },
          {
            label: "开票单位:",
            prop: "unitName", //多选时，字段要为数组类型
            propArr: "unitNameArr",
            idsStr: "unit",
            multiple: false, //是否多选
            type: "dept-select", //类型
            trigger: "change",
            methods: async (obj) => {
              let data = { orgId: obj[0].id };
              await getDeptByOrgId(data).then((res) => {
                if (res.code == 200) {
                  if (res.data == null) {
                    this.$refs.basicForm.setFormItem("unit", "");
                    this.$refs.basicForm.setFormItem("unitName", "");
                    this.$refs.basicForm.setFormItem("unitNameArr", "");
                    this.$refs.basicForm.setFormItem("department", "");
                    this.$refs.basicForm.setFormItem("departmentName", "");
                    this.$message.warning("该单位没有上级部门，请重新选择！");
                  } else {
                    this.$refs.basicForm.setFormItem("department", res.data.id);
                    this.$refs.basicForm.setFormItem(
                      "departmentName",
                      res.data.name
                    );
                  }
                }
              });
            },
            required: true,
            span: 12,
          },
          {
            label: "开票部门:",
            prop: "departmentName",
            idsStr: "department",
            type: "text",
            span: 12,
            trigger: "change",
            required: true,
            disabled: true,
          },
          {
            label: "工单编号:",
            prop: "orderCode",
            type: "location",
            span: 12,
            trigger: "change",
            required: true,
          },
          {
            label: "工作负责人:",
            prop: "directorName", //多选时，字段要为数组类型
            propArr: "directorNameArr",
            idsStr: "director",
            orgNameStr: "deptName",
            orgIdStr: "deptId",
            multiple: false, //是否多选
            isOutOrg: "", //是否是外单位;0:不是外单位；1是外单位；不做限制就不传此参数
            allowCreate: true, //是否允许创建条目
            option: [], //this.deptOption1
            type: "user-select", //类型
            defaultJob: "机电工作负责人（第三种）", //默认岗位
            trigger: "change",
            methods: (obj) => {
              this.workTeamOption = [];
              setTimeout(() => {
                this.$refs.basicForm.setItemOption(
                  "workTeamName",
                  this.workTeamOption
                );
              }, 0);
              this.handleOperateOrg();
              if (obj[0]) {
                this.externalFlag = obj[0].isOutOrg;
                this.number0 = 1;
              } else {
                this.number0 = 0;
              }
              this.number = this.number0 + this.number1;
            },
            required: true,
            span: 12,
          },
          {
            label: "工作班组:",
            prop: "workTeamName", //多选时，字段要为数组类型
            propArr: "workTeamNameArr",
            idsStr: "workTeam",
            multiple: true, //是否多选
            option: [],
            allowCreate: true, //是否允许创建条目
            type: "dept-select", //类型
            trigger: "change",
            methods: (obj, res) => {
              this.extraOrgArr = [];
              for (let i = 0; i < obj.length; i++) {
                this.extraOrgArr.push({
                  orgId: obj[i].value,
                  orgName: obj[i].label,
                  isOutOrg: obj[i].isOutOrg,
                });
              }
              this.handleOperateOrg();
            },
            required: true,
            span: 24,
          },
          {
            label: "工作班成员:",
            prop: "classUser",
            propArr: "classUserArr",
            idsStr: "classUserId",
            orgStr: "classOrgStr",
            orgNameStr: "classOrgName",
            orgIdStr: "classOrgId",
            multiple: true, //是否多选
            isOutOrg: "", //是否是外单位;0:不是外单位；1是外单位；不做限制就不传此参数
            allowCreate: true, //是否允许创建条目
            option: [], //this.deptOption1
            type: "user-select", //类型
            trigger: "change",
            isHide: false,
            methods: (data, formData) => {
              this.handleOperateOrg();
              this.number1 = data.length;
              this.number = this.number0 + this.number1;
              let arr = data.map((item) => {
                let obj = {
                  memberAccount: item.id,
                  memberName: item.label,
                  memberUnit: item.orgId,
                  memberUnitName: item.orgName,
                  type: item.isOutOrg,
                  workTicketId: this.id,
                };
                return obj;
              });
              this.$refs.basicForm.setFormItem("workMemberList", arr);
            },
            required: true,
            disabled: false,
            span: 21,
            rows: 4,
          },
          {
            label: "共几人",
            prop: "number",
            otherInfo: "signName",
            span: 3,
          },
          {
            label: "工作内容:",
            prop: "content",
            type: "textarea",
            span: 24,
            maxlength: 3000,
            autosize: true,
            required: true,
            placeholder: "请输入",
            methods: (res) => {
              if (!this.title) {
                if (res.length > 64) {
                  this.title = res.substring(0, 64);
                } else {
                  this.title = res;
                }
              }
            },
          },
          {
            label: "工作地点:",
            prop: "locationName",
            propArr: "locationNameArr",
            idsStr: "location",
            orgStr: "locationType",
            multiple: true, //是否多选
            option: [],
            allowCreate: true, //是否允许创建条目
            type: "location-select",
            trigger: "change",
            required: true,
            span: 24,
            methods: (item, res) => {
              this.locationList = [];
              item.forEach((data) => {
                let obj = {
                  location: data.isOutOrg == "-1" ? "" : data.value,
                  locationName: data.label,
                  workTicketId: this.id,
                };
                this.locationList.push(obj);
              });
            },
          },
          {
            label: "计划开始时间:",
            prop: "estimatedStartTime",
            type: "datetime",
            trigger: "change",
            span: 12,
            required: true,
            methods: (item, res) => {
              if (res.estimatedEndTime) {
                let startTime = new Date(item); //选择时间
                let endTime = new Date(res.estimatedEndTime);
                if (startTime.getTime() >= endTime.getTime()) {
                  this.$message.error("计划开始时间应小于计划结束时间");
                  res = Object.assign({}, res, { estimatedStartTime: "" });
                  this.basicFormData = Object.assign({}, res);
                }
              }
            },
          },
          {
            label: "计划结束时间:",
            prop: "estimatedEndTime",
            type: "datetime",
            trigger: "change",
            span: 12,
            required: true,
            methods: (item, res) => {
              if (res.estimatedStartTime) {
                let endTime = new Date(item); //选择时间
                let startTime = new Date(res.estimatedStartTime);
                if (endTime.getTime() <= startTime.getTime()) {
                  this.$message.error("计划结束时间应大于计划开始时间");
                  this.basicFormData = Object.assign({}, res, {
                    estimatedEndTime: "",
                  });
                }
              }
            },
          },
          {
            label: "安全措施（注意事项）:",
            prop: "safetyMeasures",
            type: "textarea",
            autosize: true,
            required: true,
            span: 24,
            maxlength: 3000,
            placeholder: "请输入",
          },
          // {
          //   /* 缺陷工单、正常维护 */
          //   label: "通知对象",
          //   prop: "noticeUserName", //多选时，字段要为数组类型
          //   propArr: "noticeArr",
          //   idsStr: "noticeUser",
          //   multiple: true, //是否多选
          //   isOutOrg: 0,
          //   allowCreate: false, //是否允许创建条目
          //   option: [], //当前选中的项
          //   type: "userOnly-select", //类型
          //   trigger: "change",
          //   methods: (data) => {
          //     let topicWorker = data.map((item) => {
          //       let obj = {
          //         name: item.name,
          //         nameBy: item.id,
          //         account: item.account,
          //       };
          //       return obj;
          //     });
          //     this.$refs.dispatchForm.setFormItem(
          //       "topicWorker",
          //       JSON.stringify(topicWorker)
          //     );
          //   },
          //   rows: 3,
          //   span: 24,
          // },
        ],
      },
      // 基本信息表单数据
      basicFormData: {},
      // 许可信息表单
      licenseConfig: {
        labelWidth: "200px",
        itemArr: [
          {
            label: "许可开始工作时间:",
            prop: "workTime",
            type: "datetime",
            span: 12,
            required: true,
            // methods: (item, res) => {
            //   this.isEdit = 0;
            //   let date = new Date(item); //选择的时间
            //   let dateNow = new Date(); //当前时间
            //   if (date.getTime() > dateNow.getTime()) {
            //     this.$message.error("不能选择未来时间！");
            //     this.licenseFormData = Object.assign({}, res, { workTime: "" });
            //   }
            // },
          },
          {
            label: "工作跟踪责任人:",
            prop: "name2",
            type: "text",
            placeholder: "点击签名验证",
            span: 12,
            required: true,
            isHide: true,
            focusMethod: (item) => {
              this.$refs.licenseForm.setFormItem("type2", item.prop);
              this.showTemporary = true;
              let obj = {
                formData: "licenseForm",
                account: "account2",
                phone: "phone2",
                name: "name2",
                disAccount: "",
                mustAccount: "",
                position: "任何人",
              };
              this.$refs.sign.openSign(obj);
            },
          },
          {
            label: "工作负责人:",
            prop: "name1",
            type: "text",
            placeholder: "点击签名验证",
            span: 12,
            required: true,
            isHide: true,
            focusMethod: (item, res) => {
              this.$refs.licenseForm.setFormItem("type1", item.prop);
              this.showTemporary = true;
              let obj = {
                formData: "licenseForm",
                account: "account1",
                phone: "phone1",
                name: "name1",
                disAccount: res.account0 || "",
                mustAccount: this.basicFormData.director,
                position: "机电工作负责人（第三种）",
              };
              this.$refs.sign.openSign(obj);
            },
          },
          {
            label: "工作许可人:",
            prop: "name0",
            type: "text",
            placeholder: "点击签名验证",
            span: 12,
            required: true,
            isHide: true,
            focusMethod: (item, res) => {
              this.$refs.licenseForm.setFormItem("type0", item.prop);
              this.showTemporary = false;
              let obj = {
                formData: "licenseForm",
                account: "account0",
                phone: "phone0",
                name: "name0",
                disAccount: res.account1 || "",
                mustAccount: "",
                position: "工作许可人",
              };
              this.$refs.sign.openSign(obj);
            },
          },
          {
            label: "工作跟踪责任人:",
            prop: "name2", //多选时，字段要为数组类型
            propArr: "name2Arr",
            multiple: false, //是否多选
            isOutOrg: "", //是否是外单位
            allowCreate: true, //是否允许创建条目
            option: [], //当前选中的项
            type: "user-select", //类型
            trigger: "change",
            required: true,
            isHide: true,
            methods: (obj) => {
              this.isEdit = 0;
              this.setVal("licenseForm", 2, obj[0], 1);
            },
            span: 12,
          },
          {
            label: "工作许可人:",
            prop: "name0", //多选时，字段要为数组类型
            propArr: "name0Arr",
            idsStr: "account",
            multiple: false, //是否多选
            isOutOrg: "", //是否是外单位
            allowCreate: true, //是否允许创建条目
            option: [], //当前选中的项
            type: "user-select", //类型
            trigger: "change",
            isHide: true,
            methods: (obj, res) => {
              this.isEdit = 0;
              if (res.account1 && res.account1 == obj[0].account) {
                this.$message.error("工作负责人和工作许可人不能为同一人");
                this.licenseFormData = Object.assign({}, res, {
                  name0: "",
                  name0Arr: "",
                });
              } else {
                this.setVal("licenseForm", 0, obj[0], 1);
              }
            },
            required: true,
            span: 12,
          },
          {
            label: "工作负责人:",
            prop: "name1", //多选时，字段要为数组类型
            propArr: "name1Arr",
            idsStr: "account",
            multiple: false, //是否多选
            isOutOrg: "", //是否是外单位
            allowCreate: true, //是否允许创建条目
            option: [], //当前选中的项
            type: "user-select", //类型
            trigger: "change",
            isHide: true,
            methods: (obj, res) => {
              this.isEdit = 0;
              if (res.account0 && res.account0 == obj[0].account) {
                this.$message.error("工作负责人和工作许可人不能为同一人");
                this.licenseFormData = Object.assign({}, res, {
                  name1: "",
                  name1Arr: "",
                });
              } else if (this.basicFormData.director != obj[0].account) {
                this.$message.error(
                  "许可时的工作负责人必须和填写时的工作负责人为同一人"
                );
                this.licenseFormData = Object.assign({}, res, {
                  name1: "",
                  name1Arr: "",
                });
              } else {
                this.setVal("licenseForm", 1, obj[0], 1);
              }
            },
            required: true,
            span: 12,
          },
          {
            label: "许可时间:",
            prop: "permitTime",
            type: "datetime",
            span: 12,
            placeholder: "提交成功后自动填写",
            disabled: true,
            isHide: false,
          },
        ],
      },
      // 许可信息表单数据
      licenseFormData: {},
      // 工作票终结信息表单
      endOfTicketConfig: {
        labelWidth: "200px",
        itemArr: [
          {
            label: "工作结束时间:",
            prop: "endTime",
            type: "datetime",
            span: 12,
            required: true,
            methods: (item, res) => {
              let date = new Date(item); //选择的时间
              // let dateNow = new Date(); //当前时间
              // if (date.getTime() > dateNow.getTime()) {
              //   this.$message.error("不能选择未来时间！");
              //   this.endOfTicketFormData = Object.assign({}, res, {
              //     endTime: "",
              //   });
              //   return false;
              // }
              let lastTime = new Date(this.licenseFormData.workTime); //时间下限
              if (date.getTime() < lastTime.getTime()) {
                this.$message.error("工作结束时间应大于许可时间");
                this.endOfTicketFormData = Object.assign({}, res, {
                  endTime: "",
                });
              }
            },
          },
          {
            label: "工作负责人:",
            prop: "name0",
            type: "text",
            placeholder: "点击签名验证",
            span: 12,
            required: true,
            isHide: true,
            focusMethod: (item, res) => {
              this.$refs.endOfWorkTicketForm.setFormItem("type0", item.prop);
              this.showTemporary = true;
              let obj = {
                formData: "endOfWorkTicketForm",
                account: "account0",
                phone: "phone0",
                name: "name0",
                disAccount: res.account1 || "",
                mustAccount: "",
                position: "机电工作负责人（第三种）",
              };
              this.$refs.sign.openSign(obj);
            },
          },
          {
            label: "工作负责人:",
            prop: "name0", //多选时，字段要为数组类型
            propArr: "name0Arr",
            multiple: false, //是否多选
            isOutOrg: "", //是否是外单位
            allowCreate: true, //是否允许创建条目
            option: [], //当前选中的项
            type: "user-select", //类型
            trigger: "change",
            isHide: true,
            methods: (obj) => {
              this.setVal("endOfWorkTicketForm", 0, obj[0], 1);
            },
            required: true,
            span: 12,
          },
          {
            label: "工作许可人:",
            prop: "name1",
            type: "text",
            placeholder: "点击签名验证",
            span: 12,
            required: true,
            isHide: true,
            focusMethod: (item, res) => {
              this.$refs.endOfWorkTicketForm.setFormItem("type1", item.prop);
              this.showTemporary = false;
              let obj = {
                formData: "endOfWorkTicketForm",
                account: "account1",
                phone: "phone1",
                name: "name1",
                disAccount: res.account0 || "",
                mustAccount: "",
                position: "工作许可人",
              };
              this.$refs.sign.openSign(obj);
            },
          },
          {
            label: "工作许可人:",
            prop: "name1", //多选时，字段要为数组类型
            propArr: "name1Arr",
            multiple: false, //是否多选
            isOutOrg: "", //是否是外单位
            allowCreate: true, //是否允许创建条目
            option: [], //当前选中的项
            type: "user-select", //类型
            trigger: "change",
            isHide: true,
            methods: (obj) => {
              this.setVal("endOfWorkTicketForm", 1, obj[0], 1);
            },
            required: true,
            span: 12,
          },
          {
            label: "备注:",
            prop: "endDescription",
            type: "textarea",
            span: 24,
            autosize: true,
            required: true,
          },
        ],
      },
      // 工作票终结信息表单数据
      endOfTicketFormData: {},
      formDataFlow: {}, // 工作流数据
    };
  },
  computed: {
    // 操作按钮
    rightBtnArr() {
      let arr = [
        {
          text: "抽查",
          icon: "icon-choucha-244",
          disabled: !this.$store.getters.isBtnAuth("toCheck"),
          content: "未授权的功能",
          hide: this.pageType != "check",
          methods: () => {
            this.showRemarks = true;
            this.dialogTitle = "抽查";
            this.$nextTick(() => {
              this.$refs.remarkOrCheck.showDialog();
            });
          },
        },
        // 电子签
        // {
        //   text: "签名",
        //   icon: "el-icon-top-right",
        //   hide:
        //     !(this.status != 1 && this.accounts == 1 && this.signType == 1) ||
        //     !(this.status != 8 && this.accounts == 1 && this.signType == 1),
        //   methods: () => {
        //     if (
        //       (this.isEdit == 0 && this.status == 5) ||
        //       (this.status == 5 && this.isSave == 1) ||
        //       this.isSave == 1
        //     ) {
        //       this.$message.warning("请先保存！");
        //     } else if (this.previewed == 1 && this.status == 5) {
        //       this.$message.warning("请先预览！");
        //     } else {
        //       this.$refs.electronicSign.openElectronicSign();
        //     }
        //   },
        // },
        // {
        //   text: "重新签名",
        //   icon: "el-icon-top-right",
        //   hide: !(
        //     this.status != 1 &&
        //     this.accounts == 2 &&
        //     this.signType == 1 &&
        //     this.isReSign == 1
        //   ),
        //   methods: () => {
        //     this.reSign();
        //   },
        // },
        // {
        //   text: "刷新签名状态",
        //   icon: "el-icon-top-right",
        //   hide: !(
        //     this.status != 1 &&
        //     this.accounts == 2 &&
        //     this.signType == 1 &&
        //     this.isReSign == 1
        //   ),
        //   methods: () => {
        //     this.refreshStatus();
        //   },
        // },
        {
          text: "预览",
          icon: "icon-dayin",
          hide: this.hidePreviewBtn,
          disabled: !this.$store.getters.isBtnAuth("toView"),
          content: "未授权的功能",
          methods: async () => {
            if (this.status == 8 || !this.showMore) {
              this.preview();
            } else {
              if (this.$utils.getJurisdiction(this.btnPowerList, "save")) {
                if (this.status == 1) {
                  await this.save(1);
                } else {
                  await this.saveInfo();
                }
              }
              this.preview();
            }
          },
        },
        {
          text: "保存",
          icon: "icon-baocun",
          hide: this.hideSaveBtn,
          content: this.$utils.getJurisdictionContent(
            this.btnPowerList,
            "save"
          ),
          disabled: !this.id
            ? false
            : !this.$utils.getJurisdiction(this.btnPowerList, "save"),
          methods: () => {
            this.saveInfo(1);
          },
        },
        {
          text: "删除",
          icon: "icon-shanchu",
          hide: this.hideDeleteBtn,
          content: this.$utils.getJurisdictionContent(
            this.btnPowerList,
            "delete"
          ),
          disabled: !this.$utils.getJurisdiction(this.btnPowerList, "delete"),
          methods: () => {
            this.delete();
          },
        },
      ];
      return arr;
    },
    // 更多按钮
    moreBtnArr() {
      let arr = [
        {
          text: "申请操作票",
          hide: this.hideOperationBtn,
          content: this.$utils.getJurisdictionContent(
            this.btnPowerList,
            "operationTicket"
          ),
          disabled: !this.$utils.getJurisdiction(
            this.btnPowerList,
            "operationTicket"
          ),
          methods: (item) => {
            let data = {
              workTicketId: this.id,
              pageType: "workTicket",
              id: item.id,
            };
            this.$emit("goOperationTicket", data);
          },
          isDictionary: true, //是否是数据字典
          child: [
            {
              id: 1,
              label: "厂站操作票",
            },
            {
              id: 2,
              label: "调度操作票",
            },
          ],
        },
        // {
        //   text: "查看操作票",
        //   hide: this.status != 5,
        //   methods: () => {},
        // },
        {
          text: "备注",
          content: this.$utils.getJurisdictionContent(
            this.btnPowerList,
            "note"
          ),
          disabled: !this.id
            ? false
            : !this.$utils.getJurisdiction(this.btnPowerList, "note"),
          methods: (disabled) => {
            if (!disabled) {
              this.showRemarks = true;
              this.dialogTitle = "备注";
              this.$nextTick(() => {
                this.$refs.remarkOrCheck.showDialog();
              });
            }
          },
        },
        {
          text: "操作记录",
          disabled: !this.$store.getters.isBtnAuth("operateLog"),
          content: "未授权的功能",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
        },
        {
          text: "查看流程",
          hide: this.status == 1,
          disabled: !this.$store.getters.isBtnAuth("seeFlow"),
          content: "未授权的功能",
          methods: () => {
            this.formDataFlow = { id: this.id };
            this.showDialogFlow = true;
          },
        },
      ];
      return arr;
    },
    // 步骤设置
    stepConfig() {
      let obj = {
        nowStep: this.nowStepIndex, //当前步骤，对应stepItem数组的下标，从0开始
        stepItem: ["填写", "许可", "工作票终结", "已归档"],
      };
      return obj;
    },
    //是否展示JSA
    showJSA() {
      return (
        this.$store.getters.currentAppInfo.appCode == "xhsw" && this.status == 8
      );
    },
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    // 页面初始化信息
    init() {
      let ticketType = "ThirdTicket";
      let types = this.$store.getters["dirtData"]("ticket_work_type");
      let obj = types.find((i) => i.value == ticketType);
      this.pageName = obj ? obj.label : ticketType;
      this.pageType = this.$route.query.pageType;
      this.formData = this.$route.query.val;
      this.attachSetting.businessId = this.formData;
      if (this.pageType === "details" || this.pageType === "edit") {
        // 详情
        this.id = this.formData;
        this.getDetails(this.id);
      } else if (this.pageType === "check") {
        // 抽查
        this.id = this.formData;
        this.getDetails(this.id);
      } else if (this.pageType === "orderAdd") {
        // 工单开工作票
        this.addOrImportInfo(this.pageType);
        this.formData = JSON.parse(this.formData);
        this.getOrderData(this.formData.orderId, this.formData.orderCode);
      } else {
        // 新增、历史票或样票导入
        this.addOrImportInfo(this.pageType);
      }
    },
    // 新增或导入初始化部分信息
    async addOrImportInfo() {
      this.hideSaveBtn = false;
      this.activeNames = ["1"];
      this.showInput = true;
      if (this.$store.state.user.userInfo.deptName == null) {
        this.$message.warning("您所属的单位没有上级部门，请重新选择开票单位！");
      } else {
        this.$set(
          this.basicFormData,
          "unit",
          this.$store.state.user.userInfo.orgId
        );
        this.$set(
          this.basicFormData,
          "unitName",
          this.$store.state.user.userInfo.orgName
        );
        this.$set(
          this.basicFormData,
          "unitNameArr",
          this.$store.state.user.userInfo.orgName
        );
        this.$set(
          this.basicFormData,
          "department",
          this.$store.state.user.userInfo.deptId
        );
        this.$set(
          this.basicFormData,
          "departmentName",
          this.$store.state.user.userInfo.deptName
        );
      }
      this.$set(this.basicFormData, "type$", this.pageName);
      this.$set(this.basicFormData, "type", "ThirdTicket");
      if (this.pageType == "historyImport" || this.pageType == "sampleImport") {
        let res = {};
        if (this.pageType == "historyImport") {
          let { data } = await getWorkTicketInfo({ id: this.formData });
          res = data;
        } else if (this.pageType == "sampleImport") {
          let { data } = await getSampleTicketData({ id: this.formData });
          res = data;
        }
        this.title = res.title;
        this.$set(this.basicFormData, "content", res.content);
        this.$set(
          this.basicFormData,
          "safetyMeasures",
          res.workInfo.safetyMeasures || ""
        );
      }
    },
    //设置工作班组选择的数据
    getOptionInfo(nameStr, idStr, isOutOrgStr) {
      let option = [];
      let nameArr = nameStr == null ? [] : nameStr.split(",");
      let idArr = idStr == null ? [] : idStr.split(",");
      let isOutOrgArr = isOutOrgStr == null ? [] : isOutOrgStr.split(",");
      nameArr.map((i, index) => {
        let item = {
          label: i,
          value: idArr[index],
          isOutOrg: isOutOrgArr[index] || "0",
        };
        option.push(item);
      });
      return option;
    },
    getOptionData(nameArr, idArr, orgArr, orgName, orgId) {
      let option = [];
      nameArr.map((i, index) => {
        let item = {
          label: i,
          value: `${idArr[index]}${orgId[index]}`,
          id: idArr[index],
          isOutOrg: orgArr[index],
          orgName: orgName[index],
          orgId: orgId[index],
        };
        option.push(item);
      });
      return option;
    },
    //数组去重
    isRepeat(data) {
      let result = [];
      let obj = {};
      for (let i = 0; i < data.length; i++) {
        if (!obj[data[i].orgId]) {
          result.push(data[i]);
          obj[data[i].orgId] = true;
        }
      }
      return result;
    },
    //处理工作班组
    handleOperateOrg() {
      let arr = [];
      let org = [];
      let formData = this.$refs.basicForm.getCurrentData();
      if (formData.deptName) {
        org.push({
          orgId: formData.deptId,
          orgName: formData.deptName,
        });
      }
      if (formData.classOrgName) {
        formData.classOrgName
          .toString()
          .split(",")
          .forEach((item, index) => {
            if (item != "") {
              let obj = {
                orgId: formData.classOrgId.toString().split(",")[index],
                orgName: item,
              };
              org.push(obj);
            }
          });
      }
      this.orgArr = this.isRepeat(org);
      arr = [...this.extraOrgArr, ...this.orderWorkDeptPoList, ...this.orgArr];
      arr = this.isRepeat(arr);
      let workTeamName = arr.map((item) => item.orgName).join(",");
      let workTeam = arr.map((item) => item.orgId).join(",");
      let workTeamIsOut = arr.map((item) => item.isOutOrg).join(",");
      this.workTeamOption = this.getOptionInfo(
        workTeamName,
        workTeam,
        workTeamIsOut
      );
      this.workTeamOption = arr.length ? this.workTeamOption : [];
      setTimeout(() => {
        this.$refs.basicForm.setItemOption("workTeamName", this.workTeamOption);
        this.$refs.basicForm.setFormItem("workTeamName", workTeamName);
        this.$refs.basicForm.setFormItem("workTeam", workTeam);
      }, 0);
      let workTeamList = [];
      this.workTeamOption.forEach((item) => {
        let obj = {
          workTeamName: item.label,
          workTeam: item.value,
          isOutOrg: item.isOutOrg || "0",
          workTicketId: this.id,
        };
        workTeamList.push(obj);
      });
      this.$refs.basicForm.setFormItem("workTeamList", workTeamList);
    },
    // 填写状态提交
    async doSubmit() {
      this.saveOrSubmit(2);
    },
    // 填写状态保存
    async save(action) {
      let data = await this.$refs.basicForm.getCurrentData();
      let { workInfoId, department, departmentName } = data;
      let workInfo = {
        workInfo: {
          id: workInfoId,
          workTicketId: this.id,
          department,
          departmentName,
          safetyMeasures: data.safetyMeasures,
        },
      };
      let { workMemberList, workTeamList } = data;
      let {
        workTicketId,
        type,
        content,
        director,
        directorName,
        deptId,
        deptName,
        estimatedEndTime,
        estimatedStartTime,
        orderCode,
        orderId,
        orderType,
        unit,
        unitName,
      } = data;
      let workTicket = {
        workTicket: {
          id: workTicketId,
          type,
          content,
          director: director ? director.replace(/\s/g, "") : "",
          directorName: directorName ? directorName.replace(/\s/g, "") : "",
          deptId,
          deptName,
          estimatedEndTime,
          estimatedStartTime,
          orderCode,
          orderId,
          orderType,
          unit,
          unitName,
          externalFlag: this.externalFlag,
          number: this.number,
          status: 1,
          title: this.title,
          previewFlag: 1,
          updateTime: this.updateTime,
        },
      };
      let dataList = Object.assign(
        {
          createByName: this.$store.state.user.userInfo.name,
          createTime: this.$utils.getCurrentDate("minutes"),
          workLocationList: this.locationList,
        },
        workInfo,
        { workMemberList, workTeamList },
        workTicket
      );
      if (action == 0) {
        await saveTdWorkTicket(dataList).then((res) => {
          if (res.code == 200) {
            this.$message.success(res.description);
            this.updateListData();
            if (this.id) {
              this.$utils.addOperateLog(this.id, `修改了${this.pageName}`);
              this.getDetails(this.id);
            } else {
              this.id = res.data;
              let obj = {
                val: res.data,
                pageType: "edit",
                ticketType: "ThirdTicket",
              };
              this.$router.push({
                query: obj,
              });
              this.$utils.addOperateLog(res.data, `新建了${this.pageName}`);
              this.getDetails(res.data);
            }
          }
        });
      } else if (action == 1) {
        await saveTdWorkTicket(dataList);
      }
    },
    // 填写状态提交
    async submit() {
      let data = await this.$refs.basicForm.getFormData();
      let { workInfoId, department, departmentName } = data;
      let workInfo = {
        workInfo: {
          id: workInfoId,
          workTicketId: this.id,
          department,
          departmentName,
          safetyMeasures: data.safetyMeasures,
        },
      };
      let { workMemberList, workTeamList } = data;
      let {
        workTicketId,
        type,
        content,
        director,
        directorName,
        deptId,
        deptName,
        estimatedEndTime,
        estimatedStartTime,
        orderCode,
        orderId,
        orderType,
        unit,
        unitName,
      } = data;
      let workTicket = {
        workTicket: {
          id: workTicketId,
          type,
          content,
          director: director ? director.replace(/\s/g, "") : "",
          directorName: directorName ? directorName.replace(/\s/g, "") : "",
          deptId,
          deptName,
          estimatedEndTime,
          estimatedStartTime,
          orderCode,
          orderId,
          orderType,
          unit,
          unitName,
          externalFlag: this.externalFlag,
          number: this.number,
          status: 1,
          title: this.title,
          updateTime: this.updateTime,
        },
      };
      let dataList = Object.assign(
        {
          createByName: this.$store.state.user.userInfo.name,
          createTime: this.$utils.getCurrentDate("minutes"),
          workLocationList: this.locationList,
        },
        workInfo,
        { workMemberList, workTeamList },
        workTicket,
        { workTicketId: workTicketId }
      );
      let val = Object.assign(
        { id: this.id, status: 1, title: this.title, code: this.id },
        dataList
      );
      this.formDataFlow = val;
    },
    // 任意状态保存按钮
    async saveInfo(action) {
      this.rightBtnArr[2].disabled = true;
      if (this.status == 1) {
        this.save(0);
      } else {
        let workInfo = {
          status: this.status,
          workTicketId: this.id,
        };
        let actionApi = () => {};
        let data = {};
        if (this.status == 5) {
          data = await this.$refs.licenseForm.getCurrentData();
          let list = [];
          for (let i = 0; i < 3; i++) {
            let flag = data["name" + i];
            if (flag) {
              let obj = Object.assign(
                {
                  id: this.workFlowIdList["workFlowId" + i],
                  deleteFlag:
                    this.workFlowTypeList["signType" + i] == undefined
                      ? this.signType
                      : this.workFlowTypeList["signType" + i],
                  account: data["account" + i],
                  phone: data["phone" + i],
                  name: data["name" + i],
                  type: data["type" + i],
                  operationTime: data.workTime,
                },
                workInfo
              );
              list.push(obj);
              delete data["account" + i];
              delete data["phone" + i];
              delete data["name" + i];
              delete data["type" + i];
            }
          }
          data = Object.assign(
            data,
            { workTicketId: this.id },
            { workFlowList: list },
            { updateTime: this.updateTime }
          );
          actionApi = (params) => {
            return tdPermitSave(params);
          };
        } else if (this.status == 7) {
          data = await this.$refs.endOfWorkTicketForm.getCurrentData();
          let list = [];
          for (let i = 0; i < 2; i++) {
            let flag = data["name" + i];
            if (flag) {
              let obj = Object.assign(
                {
                  id: this.workFlowIdList["workFlowId" + i],
                  deleteFlag:
                    this.workFlowTypeList["signType" + i] == undefined
                      ? this.signType
                      : this.workFlowTypeList["signType" + i],
                  account: data["account" + i],
                  phone: data["phone" + i],
                  name: data["name" + i],
                  type: data["type" + i],
                  operationTime: data.endTime,
                },
                workInfo
              );
              list.push(obj);
              delete data["account" + i];
              delete data["phone" + i];
              delete data["name" + i];
              delete data["type" + i];
            }
          }
          data = Object.assign(
            { workFlowList: list },
            { endDescription: data.endDescription },
            { endTime: data.endTime },
            { workTicketId: this.id },
            { id: this.endOfTicketFormData.id },
            { updateTime: this.updateTime }
          );
          actionApi = (params) => {
            return tdTicketEndSave(params);
          };
        }
        await actionApi(data).then((res) => {
          if (res.code == 200) {
            if (this.status == 5) {
              this.isEdit = 1;
            }
            if (action == 1) {
              this.$utils.addOperateLog(this.id, `修改了${this.pageName}`);
              this.$message.success(res.description);
              this.updateListData();
              this.getDetails(this.id);
            }
          }
        });
      }
    },
    async toCheckTimeOut() {
      await checkTimeOut({ id: this.id, updateTime: this.updateTime }).then(
        async (res) => {
          if (res.code == 200) {
            this.toSubmit = true;
          } else {
            this.toSubmit = false;
          }
        }
      );
    },
    // 工作流流程审核
    async doSubmits() {
      if (this.accounts == 0 || this.signType == 0) {
        let data = {};
        let workInfo = {
          status: this.status,
          workTicketId: this.id,
          deleteFlag: 0,
        };
        if (this.status == 5) {
          data = await this.$refs.licenseForm.getFormData();
          let list = [];
          for (let i = 0; i < 3; i++) {
            let flag = data["name" + i];
            if (flag) {
              let obj = Object.assign(
                {
                  workFlowId: this.workFlowIdList["workFlowId" + i],
                  account: data["account" + i],
                  phone: data["phone" + i],
                  name: data["name" + i],
                  type: data["type" + i],
                  operationTime: data.workTime,
                },
                workInfo
              );
              list.push(obj);
              delete data["account" + i];
              delete data["phone" + i];
              delete data["name" + i];
              delete data["type" + i];
            }
          }
          data = Object.assign(
            data,
            { workTicketId: this.id },
            { workFlowList: list },
            { id: this.id, workPermitId: this.licenseFormData.id },
            { updateTime: this.updateTime }
          );
        } else if (this.status == 7) {
          data = await this.$refs.endOfWorkTicketForm.getFormData();
          let list = [];
          for (let i = 0; i < 2; i++) {
            let flag = data["name" + i];
            if (flag) {
              let obj = Object.assign(
                {
                  workFlowId: this.workFlowIdList["workFlowId" + i],
                  account: data["account" + i],
                  phone: data["phone" + i],
                  name: data["name" + i],
                  type: data["type" + i],
                  operationTime: data.endTime,
                },
                workInfo
              );
              list.push(obj);
              delete data["account" + i];
              delete data["phone" + i];
              delete data["name" + i];
              delete data["type" + i];
            }
          }
          data = Object.assign(
            { workFlowList: list },
            { endDescription: data.endDescription },
            { endTime: data.endTime },
            { workTicketId: this.id },
            { id: this.id },
            { workEndId: this.endOfTicketFormData.id },
            { updateTime: this.updateTime }
          );
        }
        this.formDataFlow = Object.assign({ title: this.title }, data);
      } else {
        this.$message.warning("请先签名并刷新签名状态！");
      }
    },
    //工作流提交成功之后
    workFlowSuccess() {
      this.updateListData();
      location.reload();
    },
    //获取详情信息
    async getDetails(id) {
      this.signType = this.$store.getters.userSignType == "electronic" ? 1 : 0;
      // let time = this.$utils.getCurrentDate("minutes");
      let time = ""; // 更改需求，不默认填写时间
      this.electronicData = { workTicketId: id };
      let type = "ThirdTicket";
      let val = { id, type };
      let { data } = await getWorkTicketData(val);
      this.createBy = data.createBy;
      this.deptId = data.deptId;
      this.unit = data.workTicket.unit;
      this.unitName = data.workTicket.unitName;
      this.updateTime = data.workTicket.updateTime;
      this.creatInfo = {
        createByName: data.workTicket.createUserName,
        deptName: data.workTicket.createDeptName,
        createTime: data.workTicket.createTime,
        id: this.id,
      };
      this.previewed = data.workTicket.previewFlag;
      this.externalFlag = data.workTicket.externalFlag;
      this.status = data.workTicket.status == 9 ? 0 : data.workTicket.status;
      let appCode = this.$store.getters.currentAppInfo.appCode;
      if (this.status == 0) {
        this.code = data.workTicket.code || "暂无票号";
        this.basicFormData = data.workTicket;
        this.basicFormData.directorName = data.workTicket.directorName;
        this.basicFormData.directorNameArr = data.workTicket.director;
        this.basicFormData.director = data.workTicket.director;
        this.title = data.workTicket.title;
        this.$set(this.basicFormData, "type$", this.pageName);
        this.$set(this.basicFormData, "unitName", data.workTicket.unitName);
        this.$set(this.basicFormData, "unitNameArr", data.workTicket.unitName);
        this.$set(
          this.basicFormData,
          "departmentName",
          data.workInfo.departmentName
        );
        this.$set(
          this.basicFormData,
          "safetyMeasures",
          data.workInfo.safetyMeasures
        );
        this.setWorkLocation(data.workLocationList);
        if (data.workMemberList.length) {
          const classInfo = {
            classUser: [],
            classUserArr: [],
            classUserId: [],
            classOrgName: [],
            classOrgId: [],
            classOrgStr: [],
          };
          data.workMemberList.forEach((item) => {
            classInfo.classUser.push(item.memberName);
            classInfo.classOrgStr.push(item.type);
            if (item.memberUnit) {
              classInfo.classOrgName.push(item.memberUnitName);
              classInfo.classOrgId.push(item.memberUnit);
              classInfo.classUserId.push(item.memberAccount);
              classInfo.classUserArr.push(
                `${item.memberAccount}${item.memberUnit}`
              );
            } else {
              classInfo.classUserId.push(item.memberAccount);
              classInfo.classOrgName.push("");
              classInfo.classOrgId.push("");
              classInfo.classUserArr.push(item.memberName);
            }
            return;
          });
          this.basicFormData.classUser = classInfo.classUser.join(",");
          this.basicFormData.classUserId = classInfo.classUserId.join(",");
          this.basicFormData.classOrgName = classInfo.classOrgName.join(",");
          this.basicFormData.classOrgId = classInfo.classOrgId.join(",");
          this.basicFormData.classOrgStr = classInfo.classOrgStr.join(",");
          this.basicFormData.classUserArr = classInfo.classUserArr;
          this.userOption = this.getOptionData(
            classInfo.classUser,
            classInfo.classUserId,
            classInfo.classOrgStr,
            classInfo.classOrgName,
            classInfo.classOrgId
          );
          let obj = {
            id: data.workTicket.director || "",
            isOutOrg: data.workTicket.externalFlag
              ? data.workTicket.externalFlag.toString()
              : "0",
            label: data.workTicket.directorName || "",
            orgId: data.workTicket.deptId || "",
            orgName: data.workTicket.deptName || "",
            value:
              data.workTicket.director || "" + data.workTicket.deptId || "",
          };
          setTimeout(() => {
            this.$refs.basicForm.setItemOption("classUser", this.userOption);
            this.$refs.basicForm.setItemOption("directorName", [obj]);
            this.$refs.basicForm.setFormItem(
              "classUserArr",
              classInfo.classUserArr
            );
          }, 0);
          let workMemberList = [];
          for (let i = 0; i < data.workMemberList.length; i++) {
            let {
              memberName,
              memberAccount,
              memberUnit,
              memberUnitName,
              type,
            } = data.workMemberList[i];
            let workTicketId = this.id;
            workMemberList.push({
              memberAccount,
              memberName,
              memberUnit,
              memberUnitName,
              type,
              workTicketId,
            });
          }
        }
        if (data.workTeamList.length) {
          this.extraOrgArr = [];
          const teamInfo = {
            teamName: [],
            teamId: [],
            workTeamIsOut: [],
          };
          data.workTeamList.forEach((item) => {
            this.extraOrgArr.push({
              orgId: item.workTeam,
              orgName: item.workTeamName,
              isOutOrg: item.isOutOrg,
            });
            teamInfo.teamName.push(item.workTeamName);
            teamInfo.teamId.push(item.workTeam);
            teamInfo.workTeamIsOut.push(item.isOutOrg);
          });
          this.workTeamOption = this.getOptionInfo(
            teamInfo.teamName.toString(),
            teamInfo.teamId.toString(),
            teamInfo.workTeamIsOut.toString()
          );
          setTimeout(() => {
            this.$refs.basicForm.setItemOption(
              "workTeamName",
              this.workTeamOption
            );
            this.$refs.basicForm.setFormItem(
              "workTeamNameArr",
              teamInfo.teamId
            );
            this.$refs.basicForm.setFormItem("workTeamName", teamInfo.teamName);
            this.$refs.basicForm.setFormItem("workTeam", teamInfo.teamId);
            this.handleOperateOrg();
          }, 0);
        }
        this.number = data.workTicket.number;
        this.workOrderDisable = true;
        this.showBtn = false;
        this.showInput = false;
        this.basicConfig.itemArr.map((i) => (i.disabled = true));
        this.status = 1;
        this.activeNames.push(this.status.toString());
        let types = data.workFlowList;
        let obj = types.find((i) => i.status == 5);
        if (obj) {
          this.licenseFormData = data.workPermit;
          for (let i = 0; i < 3; i++) {
            let types = data.workFlowList;
            let name = "name" + i;
            let obj2 = types.find((i) => i.status == 5 && i.type == name);
            if (obj2) {
              this.setName("licenseForm", i, obj2);
            }
          }
          this.setSign("licenseConfig", true);
          this.setSignConfig("licenseConfig", true);
          if (this.externalFlag == 0) {
            if (this.signType == 1) {
              this.licenseConfig.itemArr[4].isHide = true;
            } else {
              this.licenseConfig.itemArr[1].isHide = true;
            }
          }
          this.status = 5;
          this.activeNames.push(this.status.toString());
          let types = data.workFlowList;
          let obj = types.find((i) => i.status == 7);
          if (obj) {
            if (this.externalFlag == 0) {
              if (this.signType == 1) {
                this.licenseConfig.itemArr[4].isHide = true;
              } else {
                this.licenseConfig.itemArr[1].isHide = true;
              }
            }
            let types = data.workFlowList;
            for (let i = 0; i < 2; i++) {
              let name = "name" + i;

              let obj2 = types.find((i) => i.status == 7 && i.type == name);
              if (obj2) {
                this.setName("endOfWorkTicketForm", i, obj2);
              }
            }
            let list = data.workEndList || [];
            let listObj = list.find((i) => i.status == 7);
            this.$set(
              this.endOfTicketFormData,
              "id",
              listObj ? listObj.id : ""
            );
            this.$set(
              this.endOfTicketFormData,
              "endTime",
              listObj ? listObj.endTime : time
            );
            this.$set(
              this.endOfTicketFormData,
              "endDescription",
              listObj ? listObj.endDescription : "无"
            );
            this.endDisable = true;
            this.setSign("endOfTicketConfig", true);
            this.setSignConfig("endOfTicketConfig", true);
            this.status = 7;
            this.activeNames.push(this.status.toString());
          }
        }
        this.nowStepIndex =
          this.status == 1
            ? 0
            : this.status == 5
            ? 1
            : this.status == 7
            ? 2
            : 3;
        this.showMore = false;
        this.rightBtnArr.map((i) => (i.hide = true));
        this.rightBtnArr[1].hide = false; // 作废可预览
        this.stepConfig.stepItem[this.stepConfig.nowStep] += "(已作废)";
      } else {
        this.showMore = true;
        await getPower(id, this.status, "ThirdTicket").then((res) => {
          if (res.code == 200) {
            let list = [];
            res.data.det.forEach((item) => {
              let obj = {
                code: item.code,
                rule: item.msg || "",
                jurisdiction: !item.isPower,
              };
              list.push(obj);
            });
            this.btnPowerList = list;
          }
        });
        this.$set(this.basicFormData, "unitNameArr", data.workTicket.unitName);
        this.nowStepIndex =
          this.status == 1
            ? 0
            : this.status == 5
            ? 1
            : this.status == 7
            ? 2
            : 3;
        this.activeNames = [];
        this.showFlow =
          this.status == 1 &&
          !this.$utils.getJurisdiction(this.btnPowerList, "save")
            ? false
            : true;
        this.formDataFlow = {
          id: this.id,
          createBy: this.createBy,
          deptId: this.deptId,
          unit: this.unit,
          unitName: this.unitName,
        };
        this.activeNames.push("8");
        this.activeNames.push(this.status.toString());
        this.electronicData = {
          workTicketId: id,
          title:
            this.pageName +
            "-" +
            this.stepConfig.stepItem[this.nowStepIndex] +
            "状态-签名文档",
          createName: "杨敏",
          creatorContact: "18616149821",
          workFlowIdList: this.workFlowIdList,
          status: this.status,
        };
        if (this.status == 1) {
          this.showInput = true;
          if (!this.$utils.getJurisdiction(this.btnPowerList, "save")) {
            // 无保存、提交、编辑权限
            this.basicConfig.itemArr.forEach((item) => {
              item.disabled = true;
            });
            this.workOrderDisable = true;
            this.showBtn = false;
          }
          this.hidePreviewBtn = false;
          this.hideSaveBtn = false;
          this.hideDeleteBtn = false;
          this.showBtn == true;
          this.isSave = 0;
        }
        this.code = data.workTicket.code || "暂无票号";
        this.title = data.workTicket.title;
        this.$set(this.basicFormData, "workTicketId", data.workTicket.id);
        this.$set(this.basicFormData, "workInfoId", data.workInfo.id);
        this.$set(this.basicFormData, "type$", this.pageName);
        this.$set(this.basicFormData, "workTeamList", data.workTeamList);
        this.$set(this.basicFormData, "workMemberList", data.workMemberList);
        if (!data.workTicket.orderCode) {
          delete data.workTicket.orderCode;
        }
        if (!data.workTicket.estimatedStartTime) {
          delete data.workTicket.estimatedStartTime;
        }
        if (!data.workTicket.estimatedEndTime) {
          delete data.workTicket.estimatedEndTime;
        }
        this.basicFormData = Object.assign(
          {},
          this.basicFormData,
          data.workInfo,
          data.workTicket
        );
        this.setWorkLocation(data.workLocationList);
        if (data.workTicket.directorName) {
          this.number0 = 1;
          this.basicFormData.directorName = data.workTicket.directorName;
          this.basicFormData.directorNameArr = data.workTicket.director;
          this.basicFormData.director = data.workTicket.director;
          let obj = {
            id: data.workTicket.director || "",
            isOutOrg: data.workTicket.externalFlag
              ? data.workTicket.externalFlag.toString()
              : "0",
            label: data.workTicket.directorName || "",
            orgId: data.workTicket.deptId || "",
            orgName: data.workTicket.deptName || "",
            value:
              data.workTicket.director || "" + data.workTicket.deptId || "",
          };
          setTimeout(() => {
            this.$refs.basicForm.setItemOption("directorName", [obj]);
          }, 0);
        } else {
          this.number0 = 0;
        }
        this.number1 = data.workMemberList.length;
        this.number = this.number0 + this.number1;
        if (data.workMemberList.length) {
          const classInfo = {
            classUser: [],
            classUserArr: [],
            classUserId: [],
            classOrgName: [],
            classOrgId: [],
            classOrgStr: [],
          };
          data.workMemberList.forEach((item) => {
            classInfo.classUser.push(item.memberName);
            classInfo.classOrgStr.push(item.type);
            if (item.memberUnit) {
              classInfo.classOrgName.push(item.memberUnitName);
              classInfo.classOrgId.push(item.memberUnit);
              classInfo.classUserId.push(item.memberAccount);
              classInfo.classUserArr.push(
                `${item.memberAccount}${item.memberUnit}`
              );
            } else {
              classInfo.classUserId.push(item.memberAccount);
              classInfo.classOrgName.push("");
              classInfo.classOrgId.push("");
              classInfo.classUserArr.push(item.memberName);
            }
            return;
          });
          this.basicFormData.classUser = classInfo.classUser.join(",");
          this.basicFormData.classUserId = classInfo.classUserId.join(",");
          this.basicFormData.classOrgName = classInfo.classOrgName.join(",");
          this.basicFormData.classOrgId = classInfo.classOrgId.join(",");
          this.basicFormData.classOrgStr = classInfo.classOrgStr.join(",");
          this.basicFormData.classUserArr = classInfo.classUserArr;
          this.userOption = this.getOptionData(
            classInfo.classUser,
            classInfo.classUserId,
            classInfo.classOrgStr,
            classInfo.classOrgName,
            classInfo.classOrgId
          );
          setTimeout(() => {
            this.$refs.basicForm.setItemOption("classUser", this.userOption);
            this.$refs.basicForm.setFormItem(
              "classUserArr",
              classInfo.classUserArr
            );
          }, 0);
          let workMemberList = [];
          for (let i = 0; i < data.workMemberList.length; i++) {
            let {
              memberName,
              memberAccount,
              memberUnit,
              memberUnitName,
              type,
            } = data.workMemberList[i];
            let workTicketId = this.id;
            workMemberList.push({
              memberAccount,
              memberName,
              memberUnit,
              memberUnitName,
              type,
              workTicketId,
            });
          }
        }
        if (data.workTeamList.length) {
          this.extraOrgArr = [];
          const teamInfo = {
            teamName: [],
            teamId: [],
            workTeamIsOut: [],
          };
          let flag = data.workTeamList.findIndex((item) => {
            return data.workTicket.deptId == item.workTeam;
          });
          if (flag != "-1") {
            delete data.workTeamList[flag];
          }
          data.workTeamList.forEach((item) => {
            let flag = data.workMemberList.findIndex((obj) => {
              return obj.memberUnit == item.workTeam;
            });
            if (flag == "-1") {
              this.extraOrgArr.push({
                orgId: item.workTeam,
                orgName: item.workTeamName,
                isOutOrg: item.isOutOrg,
              });
              teamInfo.teamName.push(item.workTeamName);
              teamInfo.teamId.push(item.workTeam);
              teamInfo.workTeamIsOut.push(item.isOutOrg);
            }
          });
          setTimeout(() => {
            this.handleOperateOrg();
          }, 0);
        }
        if (this.status >= 5) {
          this.workOrderDisable = true;
          this.showBtn = false;
          this.showInput = false;
          this.basicConfig.itemArr.map((i) => (i.disabled = true));
          let types = data.workFlowList;
          let obj = types.find((i) => i.status == 5);
          if (obj) {
            for (let i = 0; i < 3; i++) {
              let name = "name" + i;
              let obj2 = types.find((i) => i.status == 5 && i.type == name);
              if (obj2) {
                this.setName("licenseForm", i, obj2);
              }
            }
          }
          if (this.status == 5) {
            this.hideSaveBtn = false; // 按钮权限
            this.hidePreviewBtn = false;
            this.hideOperationBtn = false;
            this.setSignConfig("licenseConfig", false);
            if (obj) {
              let sum = 0;
              let deleteFlagList = [];
              for (let i = 0; i < 3; i++) {
                let name = "name" + i;
                let obj2 = types.find((i) => i.status == 5 && i.type == name);
                if (obj2) {
                  this.workFlowIdList["workFlowId" + i] = obj2.id;
                  this.workFlowTypeList["signType" + i] = obj2.deleteFlag;
                  this.setVal("licenseFormData", i, obj2);
                  this.isSign("licenseConfig", obj2.type, obj2.deleteFlag);
                  sum += obj2.deleteFlag;
                  deleteFlagList.push(obj2.deleteFlag);
                }
              }
              let flag = sum / Object.keys(this.workFlowIdList).length;
              if (flag == 0) {
                this.accounts = 0;
              } else {
                deleteFlagList.find((item) => {
                  item == 2 ? (this.accounts = 2) : (this.accounts = 1);
                });
              }
              this.setDisSign("licenseConfig");
              this.isSave = 0;
            }
            if (!this.$utils.getJurisdiction(this.btnPowerList, "save")) {
              // 无保存、提交、编辑权限
              this.licenseConfig.itemArr.forEach((item) => {
                item.disabled = true;
              });
            }
          }
          if (this.externalFlag == 0) {
            if (this.signType == 1) {
              this.licenseConfig.itemArr[4].isHide = true;
            } else {
              this.licenseConfig.itemArr[1].isHide = true;
            }
          }
          obj ? this.setSign("licenseConfig", true) : "";
          this.$set(
            this.licenseFormData,
            "workTime",
            data.workPermit ? data.workPermit.workTime : time
          );
          this.$set(
            this.licenseFormData,
            "id",
            data.workPermit ? data.workPermit.id : ""
          );
          this.$set(
            this.licenseFormData,
            "permitTime",
            data.workPermit ? data.workPermit.permitTime : null
          );
          if (this.status >= 7) {
            this.setSignConfig("licenseConfig", true);
            if (this.externalFlag == 0) {
              if (this.signType == 1) {
                this.licenseConfig.itemArr[4].isHide = true;
              } else {
                this.licenseConfig.itemArr[1].isHide = true;
              }
            }
            let types = data.workFlowList;
            let obj = types.find((i) => i.status == 7);
            if (obj) {
              for (let i = 0; i < 2; i++) {
                let name = "name" + i;
                let obj2 = types.find((i) => i.status == 7 && i.type == name);
                if (obj2) {
                  this.setName("endOfWorkTicketForm", i, obj2);
                }
              }
            }
            if (this.status == 7) {
              this.hideSaveBtn = false; // 按钮权限
              this.hidePreviewBtn = false;
              this.hideOperationBtn = false;
              this.endDisable = false;
              let deleteFlagList = [];
              this.setSignConfig("endOfTicketConfig", false);
              if (obj) {
                let sum = 0;
                for (let i = 0; i < 2; i++) {
                  let name = "name" + i;
                  let obj2 = types.find((i) => i.status == 7 && i.type == name);
                  if (obj2) {
                    this.workFlowIdList["workFlowId" + i] = obj2.id;
                    this.workFlowTypeList["signType" + i] = obj2.deleteFlag;
                    this.setVal("endOfTicketFormData", i, obj2);
                    this.isSign(
                      "endOfTicketConfig",
                      obj2.type,
                      obj2.deleteFlag
                    );
                    sum += obj2.deleteFlag;
                    deleteFlagList.push(obj2.deleteFlag);
                  }
                }
                let flag = sum / Object.keys(this.workFlowIdList).length;
                if (flag == 0) {
                  this.accounts = 0;
                } else {
                  deleteFlagList.find((item) => {
                    item == 2 ? (this.accounts = 2) : (this.accounts = 1);
                  });
                }
                this.setDisSign("endOfTicketConfig");
                this.isSave = 0;
              }
              if (!this.$utils.getJurisdiction(this.btnPowerList, "save")) {
                // 无保存、提交、编辑权限
                this.endOfTicketConfig.itemArr.forEach((item) => {
                  item.disabled = true;
                });
              }
            }
            let list = data.workEndList || [];
            let listObj = list.find((i) => i.status == 7);
            this.$set(
              this.endOfTicketFormData,
              "id",
              listObj ? listObj.id : ""
            );
            this.$set(
              this.endOfTicketFormData,
              "endTime",
              listObj ? listObj.endTime : time
            );
            this.$set(
              this.endOfTicketFormData,
              "endDescription",
              listObj ? listObj.endDescription : "无"
            );
            obj ? this.setSign("endOfTicketConfig", true) : "";
            if (this.status == 8) {
              this.hidePreviewBtn = false;
              this.showFlow = false;
              this.endDisable = true;
              this.setSignConfig("endOfTicketConfig", true);
              this.activeNames = ["1", "5", "7", "9", "10"];
            }
          }
        }
      }
    },
    // 设置签名方式及表单可用性
    setSignConfig(signConfig, disabled) {
      this[signConfig].itemArr.map((i) => {
        if (i.prop != "permitTime") {
          i.disabled = disabled;
        }
      });
      this[signConfig].itemArr.map((i) =>
        i.type == "text" ? (this.signType === 0 ? (i.isHide = false) : "") : ""
      );
      this[signConfig].itemArr.map((i) =>
        i.type == "user-select"
          ? this.signType === 1
            ? (i.isHide = false)
            : ""
          : ""
      );
      this[signConfig].itemArr.map((i) =>
        i.type == "sign" ? (this.signType === 1 ? (i.isHide = false) : "") : ""
      );
    },
    // 设置普通签名不可用
    setDisSign(signConfig) {
      // this[signConfig].itemArr.map((i) =>
      //   i.type == "text" ? (i.disabled = true) : ""
      // );
    },
    // 设置电子签名不可用
    setSign(signConfig, disabled) {
      // this[signConfig].itemArr.map((i) =>
      //   i.type == "text" ? (i.disabled = disabled) : ""
      // );
      // this[signConfig].itemArr.map((i) =>
      //   i.type == "user-select" ? (i.type = "sign") : ""
      // );
    },
    // 电子签名是否已签名
    isSign(signConfig, signType, flag) {
      let str = signType + "Arr";
      let obj = this[signConfig].itemArr.find((i) => i.propArr == str);
      obj ? (obj.signed = flag) : "";
    },
    // 设置签名姓名账号等信息
    setName(formData, index, obj) {
      this.$nextTick(() => {
        this.$refs[formData].setFormItem("account" + index, obj.account);
        this.$refs[formData].setFormItem("phone" + index, obj.phone);
        this.$refs[formData].setFormItem("name" + index, obj.name);
        this.$refs[formData].setFormItem("type" + index, "name" + index);
      });
    },
    // 设置电子签名数据
    setVal(formData, index, obj, type) {
      let { name, phone, account } = obj;
      this.$set(this.electronicForm, [index], { name, phone });
      if (type == 1) {
        this.$refs[formData].setFormItem("account" + index, account);
        this.$refs[formData].setFormItem("phone" + index, phone);
        this.$refs[formData].setFormItem("name" + index, name);
        this.$refs[formData].setFormItem("type" + index, "name" + index);
      } else {
        this.$set(this[formData], "account" + index, account);
        this.$set(this[formData], "phone" + index, phone);
        this.$set(this[formData], "name" + index, name);
        this.$set(this[formData], "type" + index, "name" + index);
      }
    },
    // 预览
    async preview() {
      let list = { id: this.id };
      await printTdById(list).then(async (res) => {
        if (res.code == 200) {
          let url = res.data;
          if (this.status == 5) {
            this.rightBtnArr[1].disabled = true;
            list = Object.assign({}, list, { previewFlag: 0 });
            await updatePreview(list).then(async (res) => {
              if (res.code == 200) {
                this.$utils.addOperateLog(
                  this.id,
                  `保存并预览了${this.pageName}`
                );
                this.getDetails(this.id);
                this.$emit("previewTicket", url);
              }
            });
          } else {
            if (this.status == 8 || !this.showMore) {
              this.$utils.addOperateLog(this.id, `预览了${this.pageName}`);
              this.$emit("previewTicket", url);
            } else {
              this.rightBtnArr[1].disabled = true;
              this.$utils.addOperateLog(
                this.id,
                `保存并预览了${this.pageName}`
              );
              this.getDetails(this.id);
              this.$emit("previewTicket", url);
            }
          }
        }
      });
    },
    // 账号密码签名
    doSign(data, currentItem) {
      this.isEdit = 0;
      let formData = currentItem.formData;
      if (currentItem.disAccount == data.account) {
        this.$message.error("工作负责人和工作许可人不能为同一人");
      } else if (
        currentItem.mustAccount &&
        currentItem.mustAccount != data.account
      ) {
        this.$message.error("工作负责人必须和填写时的工作负责人为同一人");
      } else {
        this.$refs[formData].setFormItem(currentItem.name, data.name);
        this.$refs[formData].setFormItem(currentItem.account, data.account);
        this.$refs[formData].getFormData();
      }
    },
    // 电子签名成功
    electronicSignAfter() {
      this.visibleHelp = true;
      this.getDetails(this.id);
    },
    // // 重新签名
    // reSign() {
    //   let idList = "";
    //   switch (this.status) {
    //     case 7:
    //       idList = "" + this.workFlowId;
    //       break;
    //     case 5:
    //       if (this.workFlowId1) {
    //         idList =
    //           this.workFlowId + "," + this.workFlowId0 + "," + this.workFlowId1;
    //       } else {
    //         idList = this.workFlowId + "," + this.workFlowId0;
    //       }
    //       break;
    //   }
    //   this.$confirm(`是否重新签名`, "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   })
    //     .then(() => {
    //       deleteSign(idList).then((res) => {
    //         if (res.code == 200) {
    //           this.isReSign = 0;
    //           location.reload();
    //         }
    //       });
    //     })
    //     .catch((e) => {});
    // },
    // 刷新签名状态
    refreshStatus() {
      location.reload();
    },
    // 编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    // 编辑标题失去焦点
    loseFocus() {
      this.showInput = false;
    },
    //点击选择工单编号
    getTicketNum() {
      this.showDialogWork = true;
    },
    // 根据工单id查询工单数据
    async getOrderData(id, orderCode) {
      this.workOrderDisable = true;
      let { data } = await queryOrderById(id);
      data.orderDispatchWorker.forEach((item) => {
        item.workerJobDept = item.jobDept;
        item.workerJobDeptName = item.jobDeptName;
      });
      let val = {
        director:
          data.isOut == 1
            ? data.outLeader
              ? data.outLeader
              : data.outLeaderName
            : data.leader,
        directorName: data.isOut == 1 ? data.outLeaderName : data.leaderName,
        deptId: data.isOut == 1 ? "" : data.deptWork,
        deptName: data.isOut == 1 ? "" : data.deptWorkName,
        orderLocationList: [],
        orderCode: orderCode,
        memberNameList: data.orderDispatchWorker,
        orderType: data.orderType,
        orderId: data.orderId,
        externalFlag: data.isOut == 1 ? (data.outLeader ? "1" : "-1") : "0",
      };
      getDispatchApi(id)
        .then((res) => {
          val.orderLocationList = res.data.orderLocationList;
          this.orderWorkDeptPoList = res.data.orderWorkDeptPoList
          this.orderWorkDeptPoList = this.orderWorkDeptPoList.map(item => ({
            orgId: item.workDept,
            orgName: item.workDeptName
          }))
          // if(data.isOut == 1) {
          //   let orderWorkDeptPoList = res.data.orderWorkDeptPoList.filter(item => item.type === "outsource")
          //   this.orderWorkDeptPoList = orderWorkDeptPoList.map(item => ({
          //     orgId: item.workDept,
          //     orgName: item.workDeptName
          //   }))
          // }
          this.setOrderData(val);
        })
        .catch(() => {
          this.setOrderData(val);
        });
    },
    // 选中工单确定按钮
    async dialogSubmitWork() {
      let selectData = this.$refs.workOrderTable.getSelectData();
      let { data } = await queryOrderById(selectData.orderId);
      getDispatchApi(selectData.orderId).then(res => {
        if(data.isOut == 1) {
          let orderWorkDeptPoList = res.data.orderWorkDeptPoList.filter(item => item.type === "outsource")
          this.orderWorkDeptPoList = orderWorkDeptPoList.map(item => ({
            orgId: item.workDept,
            orgName: item.workDeptName
          }))
        }
        if (!selectData) {
          this.$message.warning("请选择一行数据！");
        } else {
          this.setOrderData(selectData);
          this.showDialogWork = false;
        }
      })
    },
    // 处理工单数据
    async setOrderData(selectData) {
      this.setWorkLocation(selectData.orderLocationList);
      let flag = true;
      if (selectData.externalFlag === "0") {
        let appId = this.$store.getters.currentAppInfo.appId;
        flag = await this.$utils.isPosition(
          selectData.director,
          "机电工作负责人（第三种）",
          appId
        );
      }
      if (flag) {
        this.basicFormData.directorName = selectData.director;
        this.basicFormData.director = selectData.director;
        this.basicFormData.directorNameArr = selectData.directorName;
        let obj = {
          id: selectData.director || "",
          isOutOrg: selectData.externalFlag.toString(),
          label: selectData.directorName || "",
          orgId: selectData.deptId || "",
          orgName: selectData.deptName || "",
          value: selectData.director || "" + selectData.deptId || "",
        };
        setTimeout(() => {
          this.$refs.basicForm.setItemOption("directorName", [obj]);
        }, 0);
      } else {
        delete selectData.directorName;
        delete selectData.director;
        delete selectData.externalFlag;
        delete selectData.deptId;
        delete selectData.deptName;
        if (!this.basicFormData.directorNameArr) {
          this.$message.warning(
            "工作负责人仅能是以下用户：机电工作负责人（第三种）、外单位人员、临时人员"
          );
        }
      }
      this.basicFormData.workMemberList = [];
      this.userOption = [];
      this.workTeamOption = [];
      setTimeout(() => {
        this.$refs.basicForm.setItemOption("classUser", this.userOption);
        this.$refs.basicForm.setItemOption("workTeamName", this.workTeamOption);
      }, 0);
      this.extraOrgArr = [];
      this.externalFlag = selectData.externalFlag;
      this.showDialogWork = false;
      if (selectData.memberNameList.length) {
        const classInfo = {
          classUser: [],
          classUserArr: [],
          classUserId: [],
          classOrgName: [],
          classOrgId: [],
          classOrgStr: [],
        };
        let workMemberList = [];
        selectData.memberNameList.forEach((item) => {
          // if(item.type === 'outsource') {
          //   item.workerName += '(外)'
          //   item.workerJobDeptName += '(外)'
          // }
          classInfo.classUser.push(item.workerName);
          if (item.workerJobDept) {
            workMemberList.push({
              memberAccount: item.worker,
              memberName: item.workerName,
              memberUnit: item.workerJobDept,
              memberUnitName: item.workerJobDeptName,
              type: "0",
              workTicketId: this.id,
            });
            classInfo.classOrgName.push(item.workerJobDeptName);
            classInfo.classOrgId.push(item.workerJobDept);
            classInfo.classUserId.push(item.worker);
            classInfo.classOrgStr.push("0");
            classInfo.classUserArr.push(`${item.worker}${item.workerJobDept}`);
          } else {
            workMemberList.push({
              memberAccount: item.worker,
              memberName: item.workerName,
              memberUnit: "",
              memberUnitName: "",
              type: "-1",
              workTicketId: this.id,
            });
            classInfo.classUserId.push(item.worker);
            classInfo.classOrgStr.push("-1");
            classInfo.classOrgName.push("");
            classInfo.classOrgId.push("");
            classInfo.classUserArr.push(item.workerName);
          }
          return;
        });
        this.basicFormData.workMemberList = workMemberList;
        this.basicFormData.classUser = classInfo.classUser.join(",");
        this.basicFormData.classUserId = classInfo.classUserId.join(",");
        this.basicFormData.classOrgName = classInfo.classOrgName.join(",");
        this.basicFormData.classOrgId = classInfo.classOrgId.join(",");
        this.basicFormData.classOrgStr = classInfo.classOrgStr.join(",");
        this.basicFormData.classUserArr = classInfo.classUserArr;
        this.userOption = this.getOptionData(
          classInfo.classUser,
          classInfo.classUserId,
          classInfo.classOrgStr,
          classInfo.classOrgName,
          classInfo.classOrgId
        );
        setTimeout(() => {
          this.$refs.basicForm.setItemOption("classUser", this.userOption);
          this.$refs.basicForm.setFormItem(
            "classUserArr",
            classInfo.classUserArr
          );
          this.handleOperateOrg();
        }, 0);
        this.number0 = selectData.directorName ? 1 : 0;
        this.number1 = classInfo.classUserId.length;
        this.number = this.number0 + this.number1;
        this.basicFormData = Object.assign({}, this.basicFormData, selectData);
      } else {
        setTimeout(() => {
          this.handleOperateOrg();
        }, 0);
        this.number0 = selectData.directorName ? 1 : 0;
        this.number1 = 0;
        this.number = this.number0 + this.number1;
        this.basicFormData = Object.assign({}, this.basicFormData, selectData);
      }
    },
    // 打开工单
    goWorkOrder(orderId, orderType) {
      this.$emit("goWorkOrder", orderId, orderType);
    },
    // 设置工作地点
    setWorkLocation(workLocationList) {
      if (workLocationList.length) {
        this.locationList = [];
        const workLocationInfo = {
          workLocationName: [],
          workLocationId: [],
          locationType: [],
        };
        workLocationList.forEach((item) => {
          let obj = {
            location: item.location || "",
            locationName: item.locationName,
            workTicketId: this.id,
          };
          this.locationList.push(obj);
          workLocationInfo.workLocationName.push(item.locationName);
          workLocationInfo.workLocationId.push(
            item.location || item.locationName
          );
          workLocationInfo.locationType.push(item.location ? "0" : "-1");
        });
        this.workLocationOption = this.getOptionInfo(
          workLocationInfo.workLocationName.toString(),
          workLocationInfo.workLocationId.toString(),
          workLocationInfo.locationType.toString()
        );
        setTimeout(() => {
          this.$refs.basicForm.setItemOption(
            "locationName",
            this.workLocationOption
          );
        }, 0);
        this.basicFormData.locationName =
          workLocationInfo.workLocationName.toString();
        this.basicFormData.locationNameArr = workLocationInfo.workLocationId;
        this.basicFormData.location =
          workLocationInfo.workLocationId.toString();
        this.basicFormData.locationType =
          workLocationInfo.locationType.toString();
      }
    },
    // 删除
    async delete() {
      let val = { id: this.id, type: "ThirdTicket",updateTime:this.basicFormData.updateTime};
      this.$emit("deleteTicket", val);
    },
    /* 更新列表页的数据 */
    updateListData() {
      this.$emit("updateListData");
    },
    //检查操作票
    async checkOperateTicket() {
      try {
        this.operationAticket = 0;
        this.operationBticket = 0;
        let res = await checkRelationPro({ workTicketId: this.id });
        let data = res.data||[];
        data.forEach((item) => {
          if (
            item.type == "operation_a" &&
            item.status == 3 &&
            this.operationAticket != 1
          ) {
            this.operationAticket = 2;
          } else if (item.type == "operation_a" && item.status != 3 && item.status != -1) {
            this.operationAticket = 1;
            this.operateTicketAId = item.id;
            this.operateAGroup = item.group;
          } else if (item.type == "operation_b" && item.status == 3 && item.status != -1) {
            this.operationBticket = 2;
          } else if (
            item.type == "operation_b" &&
            item.status != 3 &&
            this.operationBticket != 2
          ) {
            this.operationBticket = 1;
            this.operateTicketBId = item.id;
            this.operateBGroup = item.group;
          }
        });
      } catch (error) {}
    },
    //去办理操作票
    goOperateTicket(type) {
      this.show = false;
      let data = {
        workTicketId: this.id,
        pageType: "workTicket",
        id: 1,
        operateType: type,
      };
      this.$emit("goOperationTicket", data);
    },
    //跳转操作票详情页
    goOperateTicketDetail(type) {
      this.show = false;
      let data = {
        workTicketId: this.id,
        pageType: "details",
      };
      if (type == "A") {
        data.id = this.operateTicketAId;
        data.group = this.operateAGroup;
      } else {
        data.id = this.operateTicketBId;
        data.group = this.operateBGroup;
      }
      this.$emit("gotoDetails", data);
    },
    //继续提交
    continueSubmit() {
      try {
        this.show = false;
        let res = Object.assign(this.formDataFlow, {
          createBy: this.createBy,
          deptId: this.deptId,
          unit: this.unit,
          unitName: this.unitName,
        });
        this.$refs.workFlow.toSubmitFlows({
          ...this.workflowData,
          ...res,
        });
        this.$utils.addOperateLog(this.id, `审批了${this.pageName}`);
      } catch (error) {}
    },
  },
};
</script>
<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  // overflow: hidden;
  background-color: #ffffff;
  .title {
    font-size: 14px;
    font-weight: 500;
    color: #000;
    background: #f2f2f2;
    padding: 4px 10px;
    border-radius: 14px;
  }
  .el-link.el-link--primary {
    position: relative;
    right: 222px;
  }
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
  }
  /deep/ .multipleDiv .lineundefined {
    position: relative;
    top: 7px;
  }
  .basic {
    position: relative;
    .text-span {
      display: inline-block;
      height: 54px;
      line-height: 96px;
      font-size: 14px;
      color: #606266;
      .text-label {
        display: inline-block;
        height: 40px;
        line-height: 40px;
        padding: 0 10px;
        text-align: right;
        vertical-align: middle;
      }
      /deep/ .el-input {
        width: 50px;
      }
      /deep/ .el-input__inner {
        position: relative;
        top: 1px;
        display: inline-block;
        height: 28px;
        line-height: 28px;
        width: 50px;
        border: 1px solid #dcdfe6;
        padding: 0 15px;
        border: 1px solid #bababa;
        color: #666666;
        background-color: #f4f4f4;
      }
    }
  }
  .info-data {
    width: 80%;
    margin: 0 auto;
  }
  /deep/ .input-link .el-input__inner {
    color: #2c77f4;
    background-color: #f8f8f8;
  }
  /deep/ .input-link .el-input__inner:hover {
    cursor: pointer;
  }
}
</style>
